/* eslint-disable @typescript-eslint/no-explicit-any */
import { Button, Form, Input, message } from 'antd';
import styles from './login.module.less'
import { login } from '../../interfaces';
import { useNavigate, Link } from 'react-router-dom';
import { setToken } from '../../store/app-store'





function Login() {

  const navigate = useNavigate();

  const onFinish = async (values: LoginUser) => {
    try {
      const res = await login(values.username, values.password);
      if (res.status === 201 || res.status === 200) {
        message.success('登录成功');

        //返回 success 的时候，把 token 和 userInfo 存入 localStorage
        localStorage.setItem('token', res.data.token);
        localStorage.setItem('userInfo', JSON.stringify(res.data.user));
        
        setToken(res.data.token)
        setTimeout(() => {
          navigate('/');
        }, 1000)
      }
    } catch (e: any) {
      message.error(e.response?.data?.message || '系统繁忙，请稍后再试');
    }
  };



  return (
    <div className={styles.container}>
      <h1>TUTU会客室</h1>
      <Form
        onFinish={onFinish}
        colon={false}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[{ message: '请输入用户名!' }]}
          style={{ textAlign: 'center' }}
        >
          <Input

          />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{ message: '请输入密码!' }]}
          style={{ textAlign: 'center' }}
        >
          <Input.Password

          />
        </Form.Item>

        <Form.Item
        >
          <div className={styles.links}>
            <Link to='/register'>创建账号</Link>
            <Link to='/update_password'>忘记密码</Link>
          </div>
        </Form.Item>

        <Form.Item
        >
          <Button className={styles.btn} type="primary" htmlType="submit">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Login


